package com.ls.controller;

import com.ls.entity.Event;
import com.ls.event.EventProducer;
import com.ls.util.CommunityConstant;
import com.ls.util.CommunityUtil;
import com.ls.util.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author ls
 * @version v1.0
 * @description 分享
 * @date 2021/8/26 21:46
 */
@RestController
public class ShareController {

    private static final Logger logger = LoggerFactory.getLogger(ShareController.class);

    @Autowired
    private EventProducer eventProducer;

    @Value("${wk.image.storage}")
    private String wkImageStorage;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${qiniu.bucket.share.url}")
    private String shareBucketUrl;

    @GetMapping("/share")
    public R share(String htmlUrl) {
        String filename = CommunityUtil.generateUUID();
        Event event = new Event()
                .setTopic(CommunityConstant.TOPIC_SHARE)
                .setData("filename", filename)
                .setData("htmlUrl", htmlUrl)
                .setData("suffix", ".png");
        eventProducer.fireEvent(event);

        // return R.ok().put("shareUrl", domain + contextPath + "/share/image/" + filename);
        String url = shareBucketUrl + "/" + filename;
        return R.ok().put("shareUrl", url);
    }

    /**
     * 功能描述: <br>
     * 获取生成长图，废弃
     *
     * @param filename
     * @param response
     * @author ls
     * @date 2021/8/28 17:23
     * @deprecated 从本地改为七牛云获取
     */
    @Deprecated
    @GetMapping("/share/image/{filename}")
    public void getShareImage(@PathVariable("filename") String filename, HttpServletResponse response) {
        File file = new File(wkImageStorage + File.separator + filename + ".png");
        if (!file.exists()) {
            logger.info("文件不存在, filename: {}", filename);
            return;
        }
        response.setContentType("image/jpg");
        try (InputStream inputStream = new FileInputStream(file);
             OutputStream outputStream = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
                outputStream.flush();
            }
        } catch (IOException e) {
            logger.error("获取长图失败, filename: {}", filename);
            e.printStackTrace();
        }
    }

}
